#include "Bird.h"
#include "GameManager.h"
#include "GamePlayLayer.h"
#include "Utils.h"

Bird::Bird()
{
}

Bird::~Bird()
{
	
}

bool Bird::init(){
	GameObject::init();

	angle = 0;
	isRotatingTo90 = false;

	scheduleUpdate();
	sprite = CCSprite::createWithSpriteFrameName("Bird_0.png");
	sprite->setPosition(ccp(sprite->getContentSize().width/2, sprite->getContentSize().height/2));
	addChild(sprite);

	setContentSize(sprite->boundingBox().size);
	setState(BS_WAIT);

	return true;
}

void Bird::update(float delta){
	v.x += a.x*delta;
	v.y += a.y*delta;

	CCPoint position = getPosition();
	position.x += v.x * delta + 0.5 * a.x * delta * delta;
	position.y += v.y * delta + 0.5 * a.y * delta * delta;
	setPosition(position);

	if(state == BS_DIE){
		if(getPositionY() < GameManager::getInstance()->groundY){
			setState(BS_IN_GROUND);
		}
	}
	else if(state == BS_FLY){
		if(v.y < -200){
			
			rotateTo90();
		}
	}
}

void Bird::flyAnimate(){
	sprite->stopAllActions();
	CCAnimation* animation = CCAnimationCache::sharedAnimationCache()->animationByName("BirdFly");
	CCAnimate* animate = CCAnimate::create(animation);
	sprite->runAction(CCRepeatForever::create(animate));
}

void Bird::updateCameraPosition(int cameraX){
	sprite->setPositionX(sprite->boundingBox().size.width/2-cameraX);
}

void Bird::setState(int state){
	GameObject::setState(state);

	switch (state)
	{
	case BS_WAIT:
		flyAnimate();
		v.x = BIRD_VX;
		break;

	case BS_FLY:
		a.y = a.y + G;
		v.x = BIRD_VX;
		break;
		
	case BS_DIE:
		sprite->stopAllActions();
		a.x = 0;
		v.x = 0;
		GameManager::getInstance()->gamePlayLayer->shake();
		Utils::playEffect("Die");
		break;

	case BS_IN_GROUND:
		a.x = 0;
		a.y = 0;
		v.x = 0;
		v.y = 0;
		GameManager::getInstance()->gamePlayLayer->showMenu(MT_GAMEOVER);
		break;
	}
}

void Bird::flyUp(){
	v.y = BIRD_VY_FLY;
	rotateUp();
	Utils::playEffect("Wing");
}

void Bird::reset(){
	setPosition(ccp(0, 0));
	setState(BS_WAIT);
	isRotatingTo90 = false;
	setAngle(0);
}

void Bird::setAngle(float angle){
	this->angle = angle;
	sprite->setRotation(angle);
	
}

void Bird::rotateTo90(){
	if(isRotatingTo90 == false){
		isRotatingTo90 = true;

		rotateTo90Action = CCRotateTo::create(0.5, 90);

		CCCallFunc* callFuncAction = CCCallFunc::create(this, callfunc_selector(Bird::rotateDoneCallback));
		CCSequence* sequence = CCSequence::create(rotateTo90Action, callFuncAction, 0);
		sequence->setTag(1);
		sprite->runAction(sequence);
	}
}
void Bird::rotateUp(){
	isRotatingTo90 = false;
	rotateUpAction = CCRotateTo::create(0.2, -20);
	rotateUpAction->setTag(2);
	sprite->stopActionByTag(1);
	sprite->runAction(rotateUpAction);
}

void Bird::rotateDoneCallback(){
	isRotatingTo90 = false;
}